package com.xiaoma.client;

import com.xiaoma.entity.RpcRequest;
import com.xiaoma.loadbalancer.RandomLoadBalancer;
import com.xiaoma.registry.NacosServiceDiscovery;
import com.xiaoma.registry.NacosServiceRegistry;
import com.xiaoma.registry.ServiceDiscovery;
import com.xiaoma.registry.ServiceRegistry;
import com.xiaoma.server.RpcServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * @Author: xiaoma
 * @Date: 2021/7/5 13:50
 * @description:  Socket方式远程方法调用的消费者（客户端）
 */
public class SocketClient  implements RpcClient {

    private static final Logger logger = LoggerFactory.getLogger(SocketClient.class);

    private final ServiceDiscovery serviceDiscovery;

    public SocketClient() {
        this.serviceDiscovery = new NacosServiceDiscovery(new RandomLoadBalancer());
    }

    @Override
    public Object sendRequest(RpcRequest rpcRequest) {
        //在nacos上根据服务名找到对应InetSocketAddress 主机地址和端口号
        InetSocketAddress inetSocketAddress = serviceDiscovery.lookupService(rpcRequest.getInterfaceName());
        try (Socket socket = new Socket()) {
            //新建一个socket进行连接
            socket.connect(inetSocketAddress);
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
            //发出请求
            objectOutputStream.writeObject(rpcRequest);
            objectOutputStream.flush();
            //接收返回值
            Object res = objectInputStream.readObject();
            return res;
        } catch (IOException | ClassNotFoundException e) {
            logger.error("调用时有错误发生：", e);
            return null;
        }
    }
}
